#-*-coding:utf-8-*-
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Test(QTableWidget):

    def __init__(self):
        super(Test,self).__init__()

        self.setColumnCount(5)
        self.setRowCount(5)
        self.verticalHeader().setDefaultSectionSize(20)
        self.initAll()
        self.setItemFontColor()
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.rightMenu_Main)


    def initAll(self):
        """
        初始化，让所有item不为None
        :return:
        """
        for r in range(self.rowCount()):
            for c in range(self.colorCount()):
                item=QTableWidgetItem()
                item.setText('')
                self.setItem(r,c,item)


    def rightMenu_Main(self):
        mainMenu = QMenu()

        addGetTextItemAction = QAction(u'获取指定内容的item', self)
        addGetTextItemAction.triggered.connect(self._getItemByText)
        mainMenu.addAction(addGetTextItemAction)

        # 还是做一个添加颜色的吧，方便
        addColorAction = QAction(u'设置颜色')
        addColorAction.triggered.connect(self.setColor)
        mainMenu.addAction(addColorAction)

        selectedAction=QAction('当前选中的最后一个',self)
        selectedAction.triggered.connect(self._showLastOne)
        mainMenu.addAction(selectedAction)

        mainMenu.exec_(QCursor.pos())

    def setColor(self):
        '''
        主窗口 自定义item颜色,注意不要用currentItem来获取，如果没内容就返回空了，所以连背景也不能设置
        :return:
        '''
        color = QColorDialog.getColor()
        print("COLOR")
        print(color)
        r=self.currentIndex().row()
        c=self.currentIndex().column()
        item=self.item(r,c)


        temp_item = QTableWidgetItem('')

        if item is not None:
            temp_item.setText(item.text())

        temp_item.setBackground(QBrush(color))
        temp_item.setTextAlignment(Qt.AlignCenter)
        self.setItem(r, c, temp_item)

    def _showLastOne(self):
        """
        显示当前选择的最后一个
        :return:
        """
        s=self.selectedItems()
        for i in s:
            print(i.row(),i.column())


    def _getItemByText(self):
        for r in range(self.rowCount()):
            for c in range(self.columnCount()):
                if self.item(r,c):
                    if self.item(r,c).text()=='aa':
                        print(self.item(r,c))

    def setItemFontColor(self):
        item=QTableWidgetItem()
        item.setText('haha')
        item.setForeground(QBrush(QColor(255,255,0)))
        self.setItem(0,0,item)




if __name__ == '__main__':
    app=QApplication(sys.argv)
    t=Test()
    t.show()
    sys.exit(app.exec_())